CREATE FUNCTION dbo.MCCSTM_MeanTimeBetweenFailures ( @AssetPK INT )
RETURNS INT
    BEGIN

        DECLARE @CountWO INT;
        DECLARE @DaysBetween INT;
        DECLARE @AvgDay INT;


        SET @DaysBetween = ( SELECT DATEDIFF(dd, MIN(WO.Requested),
                                             MAX(WO.Requested))
                             FROM   WO WITH ( NOLOCK )
                             WHERE  WO.IsGenerated = 0
                                    AND WO.AssetPK = @AssetPK
                           );

        SET @CountWO = ( SELECT COUNT(WO.WOPK)
                         FROM   WO WITH ( NOLOCK )
                         WHERE  WO.IsGenerated = 0
                                AND WO.AssetPK = @AssetPK
                       );

        SET @AvgDay = ( CASE WHEN @CountWO = 0 THEN 0
                             WHEN @CountWO = 1 THEN 0
                             WHEN @CountWO > 1 THEN @DaysBetween / @CountWO
                             ELSE 0
                        END );

        RETURN @AvgDay;

    END;
GO